package com.wits.qso.web.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.wits.platform.common.constants.ViewType;
import com.wits.platform.common.constants.WebConstants;
import com.wits.platform.common.utils.PageUtil;
import com.wits.platform.common.utils.StringUtil;
import com.wits.platform.web.controller.BaseController;
import com.wits.platform.web.mvc.PageParam;
import com.wits.qso.entity.Cls;
import com.wits.qso.entity.Dept;
import com.wits.qso.entity.Grade;
import com.wits.qso.service.ClsService;
import com.wits.qso.service.DeptService;
import com.wits.qso.service.GradeService;

@Controller
@RequestMapping(value = "qso/cls")
public class ClsController extends BaseController{
	
	/** 注入clsService **/
	@Autowired
	private ClsService clsService;	
	@Autowired
	private DeptService deptService = null;
	@Autowired
	private GradeService gradeService = null;
	
	@RequestMapping(value="/toList")
	public String toList(){
		return "qso/cls/list";
	}
	
	/**
	 * 加载班级列表信息
	 * @param model
	 * @param page
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public String list(Model model,@ModelAttribute("page") PageParam page, HttpServletRequest req){
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(req, "search_");
		Page<Cls> listPage = clsService.findPage(Cls.class, searchParams, page);
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return PageUtil.toAjaxPageResult(listPage.getTotalElements(), listPage.getContent());
	}
	
	/**
	 * 班级列表上按钮的触发事件处理
	 * @param model
	 * @param viewType
	 * @param clsId
	 * @return
	 */
	@RequestMapping(value="/view/{viewType}")
	public String toView(Model model,@PathVariable String viewType,@RequestParam String clsId){
		if(ViewType.Add.getView().equals(viewType)){
			model.addAttribute(WebConstants.COMMAND, new Cls());
		}else{
			model.addAttribute(WebConstants.COMMAND, clsService.getOne(clsId));
		}
		logger.info( "{}", clsService.getOne(clsId) );
		model.addAttribute( "deptList", deptService.findAll() );
		model.addAttribute( "gradeList", gradeService.findAll() );
		model.addAttribute("viewType", viewType);
		
		return "qso/cls/form";
	}
	
	/**
	 * 新增、修改班级信息
	 * @param model
	 * @param command
	 * @param viewType
	 * @param result
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/save",method={RequestMethod.POST})
	@ResponseBody
	public Object save(Model model,
			@ModelAttribute("command") @Valid Cls command,
			@RequestParam String viewType,
			@RequestParam(value = "deptId") String deptId,
			@RequestParam(value = "gradeId") String gradeId,
			BindingResult result,
			HttpServletRequest req){
		if(result.hasErrors()){
			model.addAttribute(WebConstants.COMMAND, command);
			return toView(model, viewType, command.getClsId());
		}
		if(ViewType.Add.getView().equals(viewType)){
			command.setDateCre(new Date());
			command.setUserCre(getCurrentUserId());
		}else{
			command.setDateUpd(new Date());
			command.setUserUpd(getCurrentUserId());
		}
		try {
			Grade grade=gradeService.getOne( gradeId );
			Dept dept=deptService.getOne( deptId );
			command.setDept( dept );
			command.setGrade( grade );
			if(clsService.isExitsByGradeAndDept(grade, dept,command.getClsTitle())){
				return ajaxDoneError(this.getText("save.clsSaveError"));
			}else{
				clsService.save(command);
				return ajaxDoneSuccess(this.getText("save.success"));
			}
		} catch (Exception e) {
			return ajaxDoneError(this.getText("save.failed"), e);
		}
	}
	
	/**
	 * 删除班级信息
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Object delete(String ids){
		boolean hasSusscesed = false;
		boolean hasErrored = false;
		
		for(String id : Arrays.asList( StringUtil.split( ids, "," ) )) {
			try {
				clsService.delete( id );
				hasSusscesed = true;
			} catch (Exception e) {
				hasErrored = true;
			}
		}
		
		if (hasSusscesed) {
			if (hasErrored) {
				return ajaxDoneError( "有些被引用的班级无法删除" );
			} else {
				return ajaxDoneSuccess(this.getText("delete.success"));
			}
		} else {
			return ajaxDoneError( "所选班级已被引用, 无法删除" );
		}
//		try {
//			clsService.deleteInBatch(Arrays.asList(StringUtil.split(ids, ",")));
//			return ajaxDoneSuccess(this.getText("delete.success"));
//		} catch (Exception e) {
//			return ajaxDoneError(this.getText("delete.failed"), e);
//		}
	}
	
	/**
	 * 唯一键检查
	 * @param clsId
	 * @param oldClsId
	 * @return
	 */
	@RequestMapping(value="/checkUniqueId")
	@ResponseBody
	public boolean checkUniqueId(@RequestParam("clsId") String clsId,@RequestParam("oldClsId") String oldClsId){
		if(clsId.equals(oldClsId)){
			return true;
		}
		Cls obj=clsService.getOne(clsId);
		return obj == null;
	}
}
